/**
 * 页面组合键
 * @type {{}}
 */
import typeOfUtils from "../../utils/type-of-utils";
import {deepClone} from "../../utils";
import {DirectiveOptions} from "vue";
import hotkeys from 'hotkeys-js';

export const keyCom: DirectiveOptions = {
  bind(el, binding, vnode) {
    let modifiers = deepClone(binding.modifiers)
    if (typeOfUtils.isEmpty(modifiers)) {
      modifiers = { // 默认的组合键为ctrl + x
        ctrl: true,
        x: true
      }
    }
    function keyupHandler(event,handler){
      if (typeOfUtils.isFunction(binding.value)) {
        binding.value();
      } else {
        alert('页面组合键必须绑定方法')
      }
      return false
    }
    let str = Object.keys(modifiers).join('+') // 定义组合键
    hotkeys(str, keyupHandler);
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.__keyComFunc__ = keyupHandler;
    el.__keyComName__ = str;
  },
  unbind(el, binding) {
    // 解除事件监听
    hotkeys.unbind(el.__keyComName__,el.__keyComFunc__)
    delete el.__keyComFunc__;
    delete el.__keyComName__;
  },
}


/**
 * 说明文档
 * https://github.com/jaywcjlove/hotkeys/blob/master/README-zh.md
 */
